package cn.longwingstech.intelligence.agent.langchain4j;

import dev.langchain4j.mcp.McpToolProvider;
import dev.langchain4j.mcp.client.DefaultMcpClient;
import dev.langchain4j.mcp.client.McpClient;
import dev.langchain4j.mcp.client.transport.McpTransport;
import dev.langchain4j.mcp.client.transport.stdio.StdioMcpTransport;
import dev.langchain4j.service.tool.ToolProvider;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apiguardian.api.API;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.List;
@Slf4j
@Configuration
@ConfigurationProperties("langchain4j.key.mcp")
@Data
public class McpClientConfig {
    private String amapMapsApiKey;

    @Bean("mcpAmApClient")
    public McpClient mcpAmApClient() {
        // 获取当前操作系统
        String os = System.getProperty("os.name").toLowerCase();
        String exName = "npx";
        List<String> list = null;
        if (os.contains("win")) {
            exName += ".cmd";
        }
        list = List.of(
                exName
                , "-y", "@amap/amap-maps-mcp-server"
                , "-e", "AMAP_MAPS_API_KEY=" + amapMapsApiKey
        );
        log.info("初始化高德地图连接");
        McpTransport transport = new StdioMcpTransport.Builder()
                .command(list)
                .logEvents(true)
                .build();

        DefaultMcpClient build = new DefaultMcpClient.Builder()
                .pingTimeout(Duration.ofSeconds(5))
                .reconnectInterval(Duration.ofSeconds(5))
                .initializationTimeout(Duration.ofMinutes(5))
                .transport(transport)
                .build();
        log.info("初始化高德地图连接成功");
        return build;
    }
    @Bean("mcp12306Client")
    public McpClient mcp12306Client() {
        // 获取当前操作系统
        String os = System.getProperty("os.name").toLowerCase();
        String exName = "npx";
        List<String> list = null;
        if (os.contains("win")) {
            exName += ".cmd";
        }
        list = List.of(
                exName, "-y", "12306-mcp"
        );
        log.info("初始化12306-mcp连接");
        McpTransport transport = new StdioMcpTransport.Builder()
                .command(list)
                .logEvents(true)
                .build();

        DefaultMcpClient build = new DefaultMcpClient.Builder()
                .pingTimeout(Duration.ofSeconds(5))
                .reconnectInterval(Duration.ofSeconds(5))
                .initializationTimeout(Duration.ofMinutes(5))
                .transport(transport)
                .build();
        log.info("初始化12306-mcp连接成功");
        return build;
    }
    @Bean("mcpToolProvider")
    public ToolProvider mcpToolProvider(McpClient[] mcpClient) {
        return McpToolProvider.builder()
                .mcpClients(mcpClient)
                .build();
    }
}
